package com.boxuegu.boxueguapiservice.controller;


import com.boxuegu.boxueguapiservice.entity.Question;
import com.boxuegu.boxueguapiservice.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Vincent
 */
@RestController
@RequestMapping("/question")
public class QuestionController {
  @Autowired
  private QuestionService questionService;
  
  /**
   * 找回面膜并重置密码
   *
   * @param param 用户名,密保问题答案
   * @return 是否重置成功
   */
  @PostMapping("/forget")
  @ResponseBody
  public Map<String, Object> forget(@RequestBody Map<String, Object> param) {
    Map<String, Object> map = new HashMap<>();
    Question one = questionService.findOneByUserNameAndAnswer(param);
    if (one != null) {
      questionService.forgetUserPassword(one.getId());
      map.put("msg", "成功");
      map.put("success", true);
      map.put("result", "密码初始为123456");
    } else {
      map.put("msg", "失败");
      map.put("success", false);
    }
    return map;
  }
  
  /**
   * 设置密保
   *
   * @param question 问题信息
   * @return 设置是否成功
   */
  @PostMapping("/addQuestion")
  @ResponseBody
  public Map<String, Object> savaQuestion(@RequestBody Question question) {
    Map<String, Object> map = new HashMap<>();
    int result;
    try {
      result = questionService.savaQuestion(question);
    } catch (DuplicateKeyException d) {
      result = 0;
    }
    if (result == 1) {
      map.put("msg", "设置成功");
      map.put("success", true);
    } else {
      map.put("msg", "设置失败");
      map.put("success", false);
    }
    return map;
  }
  /**
   * 修改密保
   *
   * @param question 问题信息
   * @return 设置是否成功
   */
  @PostMapping("/updateQuestion")
  @ResponseBody
  public Map<String, Object> updateQuestion(@RequestBody Question question) {
    Map<String, Object> map = new HashMap<>();
    int result;
    try {
      result = questionService.updateQuestion(question);
    } catch (DuplicateKeyException d) {
      result = 0;
    }
    if (result == 1) {
      map.put("msg", "修改成功");
      map.put("success", true);
    } else {
      map.put("msg", "修改失败");
      map.put("success", false);
    }
    return map;
  }
}
